<template>
  <div class="household-list-container">
    <el-card class="household-card">
      <template #header>
        <div class="card-header">
          <span>房户管理</span>
          <div class="header-buttons">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增房户
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="所属社区">
            <el-select
              v-model="searchForm.communityId"
              placeholder="请选择社区"
              clearable
              style="width: 200px"
              @change="handleCommunityChange"
            >
              <el-option
                v-for="item in communityOptions"
                :key="item.id"
                :label="item.communityName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属楼栋">
            <el-select
              v-model="searchForm.buildingId"
              placeholder="请选择楼栋"
              clearable
              style="width: 200px"
              @change="handleBuildingChange"
            >
              <el-option
                v-for="item in filteredBuildingOptions"
                :key="item.id"
                :label="item.buildingName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属单元">
            <el-select
              v-model="searchForm.unitId"
              placeholder="请选择单元"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="item in unitOptions"
                :key="item.id"
                :label="item.unitName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="房间号">
            <el-input
              v-model="searchForm.roomNumber"
              placeholder="请输入房间号"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="房户状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="空闲" :value="0" />
              <el-option label="已入住" :value="1" />
              <el-option label="已售" :value="2" />
              <el-option label="已租" :value="3" />
              <el-option label="装修中" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 表格区域 -->
      <div class="table-area" v-if="!showEmptyState">
        <el-table
          v-loading="loading"
          :data="filteredTableData"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="roomNumber" label="房间号" width="100" />
          <el-table-column prop="buildingName" label="所属楼栋" min-width="120" />
          <el-table-column prop="unitName" label="所属单元" width="100" />
          <el-table-column prop="area" label="面积(㎡)" width="100" align="center" />
          <el-table-column prop="roomType" label="房间类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="String(getTagType(getRoomTypeTagType(row.roomType)))" size="small">
                {{ getRoomTypeText(row.roomType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="hallCount" label="客厅数" width="80" align="center" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="String(getTagType(getStatusTagType(row.status)))">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="roomType" label="房屋类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="String(getTagType(getHouseTypeTagType(row.roomType)))" size="small">
                {{ getHouseTypeText(row.roomType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="decorationStatus" label="装修状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="String(getTagType(getDecorationTagType(row.decorationStatus)))" size="small">
                {{ getDecorationText(row.decorationStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" text @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="success" size="small" text @click="handleView(row)">
                查看详情
              </el-button>
              <el-button type="danger" size="small" text @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-area" v-if="filteredTableData.length > 0">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      
      <!-- 空状态 -->
      <div class="empty-state" v-if="showEmptyState">
        <el-empty
          :description="emptyStateMessage"
          :image-size="200"
        >
          <template #description>
            <div class="empty-description">
              <p>{{ emptyStateMessage }}</p>
              <p class="empty-sub-description">{{ emptyStateDescription }}</p>
            </div>
          </template>
          <template #extra>
            <div class="empty-actions">
              <el-button type="primary" @click="handleAdd">
                <el-icon><Plus /></el-icon>
                新增房户
              </el-button>
            </div>
          </template>
        </el-empty>
      </div>
    </el-card>
    

    
    <!-- 房户详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="房户详情"
      width="80%"
      :before-close="handleDetailClose"
    >
      <div v-if="currentHouseholdDetail" class="household-detail">
        <!-- 房户详情信息 -->
        <el-card class="detail-card" shadow="never">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="房户编码">{{ currentHouseholdDetail.householdCode }}</el-descriptions-item>
            <el-descriptions-item label="房间号">{{ currentHouseholdDetail.roomNumber }}</el-descriptions-item>
            <el-descriptions-item label="所属社区">{{ currentHouseholdDetail.communityName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="所属楼栋">{{ currentHouseholdDetail.buildingName }}</el-descriptions-item>
            <el-descriptions-item label="所属单元">{{ currentHouseholdDetail.unitName }}</el-descriptions-item>
            <el-descriptions-item label="楼层号">{{ currentHouseholdDetail.floorNumber }}</el-descriptions-item>
            <el-descriptions-item label="面积">{{ currentHouseholdDetail.area }}㎡</el-descriptions-item>
            <el-descriptions-item label="使用面积">{{ currentHouseholdDetail.usableArea }}㎡</el-descriptions-item>
            <el-descriptions-item label="朝向">{{ currentHouseholdDetail.orientation || '-' }}</el-descriptions-item>
            <el-descriptions-item label="房间类型">
              <el-tag :type="getTagType(getRoomTypeTagType(currentHouseholdDetail.roomType))" size="small">
                {{ getRoomTypeText(currentHouseholdDetail.roomType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="客厅数">{{ currentHouseholdDetail.hallCount || '-' }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getTagType(getStatusTagType(currentHouseholdDetail.status))">
                {{ getStatusText(currentHouseholdDetail.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="房屋类型">
              <el-tag :type="getTagType(getHouseTypeTagType(currentHouseholdDetail.roomType))" size="small">
                {{ getHouseTypeText(currentHouseholdDetail.roomType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="物业费标准">{{ currentHouseholdDetail.propertyFeeRate }}元/㎡</el-descriptions-item>
            <el-descriptions-item label="装修状态">
              <el-tag :type="getTagType(getDecorationTagType(currentHouseholdDetail.decorationStatus))" size="small">
                {{ getDecorationText(currentHouseholdDetail.decorationStatus) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="排序">{{ currentHouseholdDetail.sortOrder }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentHouseholdDetail.createTime }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ currentHouseholdDetail.updateTime }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ currentHouseholdDetail.remark || '无' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
        
        <!-- 住户列表 -->
        <el-card class="detail-card" shadow="never" style="margin-top: 20px;">
          
          <el-table
            :data="residentList"
            border
            stripe
            v-loading="residentLoading"
            style="width: 100%"
          >
            <el-table-column prop="realName" label="姓名" min-width="100" />
            <el-table-column prop="phone" label="联系电话" min-width="120" />
            <el-table-column prop="identityNo" label="身份证号" min-width="180" />
            <el-table-column prop="residentTypeName" label="身份" min-width="100">
              <template #default="{ row }">
                <el-tag :type="getResidentTypeTagType(row.residentType)">
                  {{ row.residentTypeName }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="moveInDate" label="入住日期" min-width="120" />
            <el-table-column prop="statusName" label="状态" min-width="100">
              <template #default="{ row }">
                <el-tag :type="getResidentStatusTagType(row.status)">
                  {{ row.statusName }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" min-width="160" />
            <el-table-column label="操作" width="80" fixed="right" v-if="canManage">
              <template #default="{ row }">
                <el-button type="danger" size="small" @click="handleDeleteResident(row)">
                  <el-icon><Delete /></el-icon>
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 住户分页 -->
          <div class="pagination-area" v-if="residentList.length > 0">
            <el-pagination
              v-model:current-page="residentPagination.current"
              v-model:page-size="residentPagination.size"
              :page-sizes="[10, 20, 50, 100]"
              :total="residentPagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleResidentSizeChange"
              @current-change="handleResidentCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/**
 * 房户管理页面
 * @author Wu.Liang
 * @date 2024-12-21
 */
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { Search, Refresh, Message, Delete } from '@element-plus/icons-vue'
import { householdApi } from '@/api/household'
import { buildingApi } from '@/api/building'
import { communityApi } from '@/api/community'
import { unitApi } from '@/api/unit'
import { residentApi } from '@/api/resident'
import { HouseholdStatus, RoomType, DecorationStatus } from '@/types/region'
import { hasPermission, getDataScopeText, getDataScopeTagType } from '@/utils/permission'
import { showMessage, getTagType } from '@/utils/message'

import { useUserStore } from '@/store/user'
import { ROLE_CODES } from '@/constants/roles'

// 初始化router
const router = useRouter()

// 响应式数据
const loading = ref(false)
const tableData = ref<any[]>([])

const detailVisible = ref(false)

const currentHouseholdDetail = ref<any>(null)
const buildingOptions = ref<any[]>([])
const communityOptions = ref<any[]>([])
const unitOptions = ref<any[]>([])

// 住户相关数据
const residentList = ref<any[]>([])
const residentLoading = ref(false)
const residentPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 初始化权限信息，防止未定义报错
const userPermissionInfo = ref<{
  isSuperAdmin: boolean
  hasPropertyCompany: boolean
  propertyCompanyId: number | null
  propertyCompanyName: string
}>({
  isSuperAdmin: false,
  hasPropertyCompany: false,
  propertyCompanyId: null,
  propertyCompanyName: ''
})

// 加载用户权限信息
const loadUserPermissionInfo = async () => {
  console.log('loadUserPermissionInfo 被调用')
  try {
    const userStore = useUserStore()
    // 首先确保公司信息是最新的
    await userStore.checkAndUpdateCompanyInfo()
    
    const permission = await userStore.getUserDataScope()
    userPermissionInfo.value.isSuperAdmin = permission.isSuperAdmin
    userPermissionInfo.value.hasPropertyCompany = permission.hasPropertyCompany
    userPermissionInfo.value.propertyCompanyId = permission.companyId
    userPermissionInfo.value.propertyCompanyName = permission.companyName
  } catch (error) {
    console.error('加载用户权限信息失败:', error)
    userPermissionInfo.value.isSuperAdmin = false
    userPermissionInfo.value.hasPropertyCompany = false
    userPermissionInfo.value.propertyCompanyId = null
    userPermissionInfo.value.propertyCompanyName = ''
  }
}

// 搜索表单
const searchForm = reactive({
  communityId: undefined as number | undefined,
  buildingId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  roomNumber: '',
  status: undefined as number | undefined
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 状态映射
const statusMap: Record<number, { text: string; type: string }> = {
  [HouseholdStatus.VACANT]: { text: '空闲', type: 'info' },
  [HouseholdStatus.OCCUPIED]: { text: '已入住', type: 'success' },
  [HouseholdStatus.RENTED]: { text: '已租', type: 'primary' },
  [HouseholdStatus.DECORATING]: { text: '装修中', type: 'danger' }
}

const houseTypeMap: Record<number, { text: string; type: string }> = {
  [RoomType.ONE_ROOM]: { text: '一室', type: 'info' },
  [RoomType.TWO_ROOM]: { text: '两室', type: 'success' },
  [RoomType.THREE_ROOM]: { text: '三室', type: 'warning' },
  [RoomType.FOUR_PLUS]: { text: '四室及以上', type: 'danger' }
}

const decorationMap: Record<number, { text: string; type: string }> = {
  [DecorationStatus.ROUGH]: { text: '毛坯', type: 'info' },
  [DecorationStatus.SIMPLE]: { text: '简装', type: 'warning' },
  [DecorationStatus.FINE]: { text: '精装', type: 'success' },
  [DecorationStatus.LUXURY]: { text: '豪装', type: 'danger' }
}

const roomTypeMap: Record<number, { text: string; type: string }> = {
  1: { text: '一室', type: 'info' },
  2: { text: '两室', type: 'success' },
  3: { text: '三室', type: 'warning' },
  4: { text: '四室及以上', type: 'danger' }
}

// 权限判断computed
const isSuperAdmin = computed(() => {
  return userPermissionInfo.value.isSuperAdmin
})

const hasPropertyCompany = computed(() => {
  return userPermissionInfo.value.hasPropertyCompany
})

const canManage = computed(() => isSuperAdmin.value || hasPropertyCompany.value)

// 权限提示相关计算属性
const showPermissionTip = computed(() => {
  return !isSuperAdmin.value
})

const permissionTipTitle = computed(() => {
  return '数据权限说明'
})

const permissionTipDescription = computed(() => {
  return '您当前只能查看权限范围内的房户数据。如需查看更多数据，请联系管理员申请权限。'
})

const permissionTipType = computed(() => {
  return 'info' as const
})

// 数据权限兼容兜底方法
const getUserDataScopeArray = () => {
  // 兼容后端未返回 dataScope 字段的情况，全部数据权限
  return ['ALL']
}
const userDataScopeInfo = computed(() => getDataScopeText(getUserDataScopeArray()))
const getDataScopeTagTypeComputed = computed(() => getDataScopeTagType(getUserDataScopeArray()))

// 空状态相关计算属性
const showEmptyState = computed(() => {
  return !isSuperAdmin.value && (!filteredTableData.value || filteredTableData.value.length === 0)
})

const emptyStateMessage = computed(() => {
  if (isSuperAdmin.value) {
    return '暂无房户数据'
  }
  return '暂无权限访问房户数据'
})

const emptyStateDescription = computed(() => {
  if (isSuperAdmin.value) {
    return '当前没有房户数据，您可以点击下方按钮新增房户'
  }
  return '您当前没有房户数据的访问权限，请联系管理员申请权限'
})

// 数据权限过滤
const filteredTableData = computed((): any[] => {
  return Array.isArray(tableData.value) ? tableData.value : []
})

const filteredBuildingOptions = computed((): any[] => {
  return Array.isArray(buildingOptions.value) ? buildingOptions.value : []
})

// 操作权限相关计算属性
const canView = computed(() => {
  // 可根据实际权限判断逻辑调整
  return isSuperAdmin.value || hasPropertyCompany.value
})
const canDelete = computed(() => {
  // 可根据实际权限判断逻辑调整
  return isSuperAdmin.value || hasPropertyCompany.value
})

// 获取状态文本
const getStatusText = (status: number) => {
  return statusMap[status]?.text || '未知'
}

// 获取状态标签样式
const getStatusTagType = (status: number) => {
  return statusMap[status]?.type || 'info'
}

// 获取房屋类型文本
const getHouseTypeText = (roomType: number) => {
  return houseTypeMap[roomType]?.text || '未知'
}

// 获取房屋类型标签样式
const getHouseTypeTagType = (roomType: number) => {
  return houseTypeMap[roomType]?.type || 'info'
}

// 获取装修状态文本
const getDecorationText = (status: number) => {
  return decorationMap[status]?.text || '未知'
}

// 获取装修状态标签样式
const getDecorationTagType = (status: number) => {
  return decorationMap[status]?.type || 'info'
}

// 获取房间类型文本
const getRoomTypeText = (roomType: number) => {
  return roomTypeMap[roomType]?.text || '未知'
}

// 获取房间类型标签样式
const getRoomTypeTagType = (roomType: number) => {
  return roomTypeMap[roomType]?.type || 'info'
}

// 联系管理员
const handleContactAdmin = () => {
  showMessage({ type: 'info', message: '请联系系统管理员申请房户数据访问权限' })
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 社区变化处理
const handleCommunityChange = async (communityId: number) => {
  searchForm.buildingId = undefined
  searchForm.unitId = undefined
  buildingOptions.value = []
  unitOptions.value = []
  
  if (communityId) {
    try {
      const response = await buildingApi.getBuildingsByCommunity(communityId)
      // 过滤掉没有有效id的数据
      buildingOptions.value = (response.data || []).filter((item: any) => item.id != null)
    } catch (error) {
      showMessage({ type: 'error', message: '加载楼栋数据失败' })
      buildingOptions.value = []
    }
  }
}

// 楼栋变化处理
const handleBuildingChange = async (buildingId: number) => {
  searchForm.unitId = undefined
  unitOptions.value = []
  
  if (buildingId) {
    try {
      const response = await unitApi.getUnitsByBuilding(buildingId)
      // 过滤掉没有有效id的数据
      unitOptions.value = (response.data || []).filter((item: any) => item.id != null)
    } catch (error) {
      showMessage({ type: 'error', message: '加载单元数据失败' })
      unitOptions.value = []
    }
  }
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    communityId: undefined,
    buildingId: undefined,
    unitId: undefined,
    roomNumber: '',
    status: undefined
  })
  buildingOptions.value = []
  unitOptions.value = []
  handleSearch()
}

// 加载数据
const loadData = async () => {
  console.log('loadData 被调用')
  try {
    loading.value = true
    const params: any = {
      current: pagination.current,
      size: pagination.size
    }
    
    // 只添加有值的搜索条件
    if (searchForm.communityId !== undefined) {
      params.communityId = searchForm.communityId
    }
    if (searchForm.buildingId !== undefined) {
      params.buildingId = searchForm.buildingId
    }
    if (searchForm.unitId !== undefined) {
      params.unitId = searchForm.unitId
    }
    if (searchForm.roomNumber) {
      params.roomNumber = searchForm.roomNumber
    }
    if (searchForm.status !== undefined) {
      params.status = searchForm.status
    }
    
    console.log('房户API请求参数:', params)
    const response = await householdApi.getHouseholdPage(params)
    console.log('房户API响应:', response)
    // 确保数据是数组格式
    tableData.value = Array.isArray(response.data?.records) ? response.data.records : []
    pagination.total = response.data?.total || 0
  } catch (error) {
    console.error('加载房户列表失败:', error)
    showMessage({ type: 'error', message: '加载房户列表失败' })
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 加载社区选项
const loadCommunityOptions = async () => {
  console.log('loadCommunityOptions 被调用')
  try {
    const response = await communityApi.getCommunityList({})
    console.log('社区API响应:', response)
    // 过滤掉没有有效id的数据
    communityOptions.value = (response.data || []).filter((item: any) => item.id != null)
  } catch (error) {
    console.error('加载社区数据失败:', error)
    showMessage({ type: 'error', message: '加载社区数据失败' })
    communityOptions.value = []
  }
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

// 新增房户
const handleAdd = () => {
  router.push('/region/household/add')
}

// 编辑房户
const handleEdit = async (row: any) => {
  // 跳转到编辑页面，传递房户ID
  router.push(`/region/household/edit/${row.id}`)
}

// 查看房户详情
const handleView = async (row: any) => {
  try {
    // 获取房户详情
    const response = await householdApi.getHouseholdDetail(row.id)
    if (response.data) {
      currentHouseholdDetail.value = response.data
      detailVisible.value = true
      // 加载住户列表
      loadResidentList(row.id)
    } else {
      showMessage({ type: 'error', message: '获取房户详情失败' })
    }
  } catch (error) {
    console.error('获取房户详情失败:', error)
    showMessage({ type: 'error', message: '获取房户详情失败' })
  }
}

// 加载住户列表
const loadResidentList = async (householdId: number) => {
  try {
    residentLoading.value = true
    const params = {
      current: residentPagination.current,
      size: residentPagination.size,
      householdId: householdId
    }
    
    const response = await residentApi.getResidentList(params)
    residentList.value = Array.isArray(response.data?.records) ? response.data.records : []
    residentPagination.total = response.data?.total || 0
  } catch (error) {
    console.error('加载住户列表失败:', error)
    showMessage({ type: 'error', message: '加载住户列表失败' })
    residentList.value = []
    residentPagination.total = 0
  } finally {
    residentLoading.value = false
  }
}

// 住户分页处理
const handleResidentSizeChange = (size: number) => {
  residentPagination.size = size
  residentPagination.current = 1
  if (currentHouseholdDetail.value && currentHouseholdDetail.value.id) {
    loadResidentList(currentHouseholdDetail.value.id)
  }
}

const handleResidentCurrentChange = (current: number) => {
  residentPagination.current = current
  if (currentHouseholdDetail.value && currentHouseholdDetail.value.id) {
    loadResidentList(currentHouseholdDetail.value.id)
  }
}



// 删除住户
const handleDeleteResident = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      '确认移除该住户吗？此操作不可恢复。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await residentApi.removeResidentFromHousehold(
      currentHouseholdDetail.value.id,
      row.residentId
    )
    showMessage({ type: 'success', message: '移除成功' })
    loadResidentList(currentHouseholdDetail.value.id)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除住户失败:', error)
      showMessage({ type: 'error', message: '移除住户失败' })
    }
  }
}

// 关闭详情弹窗
const handleDetailClose = () => {
  detailVisible.value = false
  currentHouseholdDetail.value = null
  residentList.value = []
  residentPagination.current = 1
  residentPagination.total = 0
}

// 获取住户身份标签样式
const getResidentTypeTagType = (type: number) => {
  switch (type) {
    case 1: return 'success' // 户主
    case 2: return 'info'    // 家庭成员
    case 3: return 'warning' // 租客
    case 4: return 'danger'  // 临时居住
    default: return ''
  }
}

// 获取住户状态标签样式
const getResidentStatusTagType = (status: number) => {
  switch (status) {
    case 1: return 'success' // 正常居住
    case 0: return 'danger'  // 已搬出
    case 2: return 'warning' // 暂时外出
    default: return ''
  }
}

// 删除房户
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除房户"${row.roomNumber}"吗？删除后不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await householdApi.deleteHousehold(row.id)
    showMessage({ type: 'success', message: '删除成功' })
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      showMessage({ type: 'error', message: '删除失败' })
    }
  }
}



// 初始化数据
const initData = async () => {
  console.log('initData 被调用')
  try {
    // 并行加载权限信息和业务数据，互不依赖
    await Promise.all([
      loadUserPermissionInfo(), // 权限信息用于按钮显示
      loadCommunityOptions(), // 社区选项
    ]);
    
    // 房户列表和楼栋选项在社区加载完成后加载
    loadData(); // 房户列表
  } catch (error) {
    console.error('初始化数据失败:', error);
    showMessage({ type: 'error', message: '初始化数据失败' });
  }
};

// 组件挂载时初始化
onMounted(() => {
  console.log('HouseholdList 组件挂载')
  initData();
});
</script>

<style lang="scss" scoped>
.household-list-container {
  padding: 20px;
  
  .household-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-buttons {
        display: flex;
        gap: 10px;
      }
    }
    
    .permission-tip {
      margin-bottom: 20px;
      
      .permission-info {
        .data-scope-info {
          margin: 10px 0;
          
          span {
            margin-right: 10px;
            color: #606266;
          }
        }
        
        .contact-admin {
          margin-top: 10px;
        }
      }
    }
    
    .search-area {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }
    
    .table-area {
      .pagination-area {
        margin-top: 20px;
        text-align: right;
      }
    }
    
    .empty-state {
      min-height: 400px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .empty-description {
        .empty-sub-description {
          margin-top: 10px;
          color: #909399;
          font-size: 14px;
        }
      }
      
      .empty-actions {
        margin-top: 20px;
        display: flex;
        gap: 10px;
        justify-content: center;
      }
    }
  }
}
</style> 